package rest;

import java.util.Collection;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import model.PersistentEntity;
import util.WebServiceException;
import auth.SecurityManager;
import dao.GenericDAO;

@RequestScoped
@Path("/generic")
public class GenericRestWS {

	@EJB
	private GenericDAO genericDAO;

	@Inject
	private SecurityManager securityManager;

	@SuppressWarnings("unchecked")
	@GET
	@Path("public/{entityString}/")
	@Produces(MediaType.APPLICATION_JSON)
	public Collection<?> getPublicEntities(
			@PathParam("entityString") String entityString,
			@PathParam("lastSynchDate") String lastSynchDate) {
		try {
			return genericDAO.findAllPublic(Class
					.forName(entityString).asSubclass(PersistentEntity.class));
		} catch (ClassNotFoundException e) {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
	}

	@SuppressWarnings("unchecked")
	@GET
	@Path("private/{entityString}/")
	@Produces(MediaType.APPLICATION_JSON)
	public Collection<?> getPrivateEntities(
			@PathParam("entityString") String entityString) {
		try {
			return genericDAO.findAllPrivate(
					Class.forName(entityString).asSubclass(PersistentEntity.class),
					securityManager.getUser());
		} catch (ClassNotFoundException e) {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
	}

	@POST
	@Path("/")
	@Consumes(MediaType.APPLICATION_JSON)
	public void postOneWS(@PathParam("token") String token,
			@PathParam("entityString") String entityString,
			Object persistentObject) {
		try {
			genericDAO.create(persistentObject);
		} catch (NumberFormatException e) {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		} catch (WebServiceException e) {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
	}

}